<!--  -->
<template>
  <div>
    <div class="mask"></div>
    <div class="editInfoBox">
      <div class="titleBox">
        <div class="title" v-if="isTitle">
          编辑商品
          <span>序号 {{isEditWindow.isEditNum}}</span>
        </div>
        <div class="title" v-if="!isTitle">添加商品</div>
        <div class="close" @click="closeWindow">×</div>
      </div>
      <div class="productAbout">
        <!-- 基本信息 -->
        <div class="essentialInfo">
          <div class="arrow">基本信息</div>
          <ul class="infoList" style="width: 95%">
            <li class="infoItem">
              <label class="name">商品名称：</label>
               <el-popover
                style="display: inline-block; flex: 1"
                placement="bottom-start"
                width="1000"
                trigger="manual"
                :value="showSearchGoods">
                <el-input
                  style="width: 100%"
                  size="small"
                  slot="reference"
                  v-model="filingGoodsInfoVO.goodsName"
                  @focus="showSearchGoods = true"
                  @blur="showSearchGoods = false"
                />
                <div class="search-goods" style="min-height: 30px;margin: 0 -12px" v-loading="searchGoodsLoading">
                  <div
                    v-for="(item, index) in searchGoods"
                    :key="index"
                    class="show-item-name el-select-dropdown__item"
                    :class="{selected: filingGoodsInfoVO.goodsName === item.itemName}"
                    @click="filingGoodsInfoVO.goodsName = item.itemName"
                  >
                    <div class="item-name" v-html="item.showItemName"></div>
                    <template v-if="item.type === 1">
                      <span class="price color-1">
                        ￥{{item.minPrice}}
                        <template v-if="item.minPrice !== item.maxPrice">
                         ~ ￥{{item.maxPrice}}
                        </template>
                      </span>
                      <a :href="`https://www.tlwok.com/item/${item.id}`" target="_blank">立即购买</a>
                    </template>
                  </div>
                </div>
              </el-popover>
            </li>
            <li class="infoItem">
              <label class="name">商品类目：</label>
              <div style="width: 300px">
                <el-input style="width: 100%" size="small" v-model="filingGoodsInfoVO.categoryName" />
              </div>
              <div class="new-tips">商品在对应点单平台的类目</div>
            </li>
            <li class="infoItem">
              <label class="name">商品品牌：</label>
              <div style="width: 300px">
                <el-input style="width: 100%" size="small" v-model="filingGoodsInfoVO.brandName" />
              </div>
            </li>
            <!-- <li class="infoItem thirdItem">
              <label class="name">商品名称：</label>
              <textarea v-model="filingGoodsInfoVO.goodsName"></textarea>
            </li> -->
            <li class="infoItem">
              <label class="name">型号：</label>
              <div style="width: 300px">
                <el-input style="width: 100%" size="small" v-model="filingGoodsInfoVO.model" />
              </div>
            </li>
          </ul>
        </div>
        <!-- 规格价格 -->
        <div class="specPrice">
          <div class="arrow spec">规格价格</div>

          <el-row class="base-list">
            <el-col :span="8">
              <label class="r">数量：</label>
              <el-input size="small" type="text" v-model="filingGoodsInfoVO.num" />
            </el-col>
            <el-col :span="8">
              <label class="r">单位：</label>
              <el-input size="small" type="text" v-model="filingGoodsInfoVO.unit" />
            </el-col>
            <el-col :span="8">
              <label class="r">重量：</label>
              <el-input size="small" type="text" v-model="filingGoodsInfoVO.weight" >
                <template slot="append">kg</template>
              </el-input>
            </el-col>

            <el-col :span="8">
              <label class="r">挂网价：</label>
              <el-input
                size="small"
                type="text"
                @blur="blurAfter(filingGoodsInfoVO.salesPrice)"
                v-model="filingGoodsInfoVO.salesPrice"
              >
                <template slot="append">元</template>
              </el-input>
            </el-col>

            <el-col :span="10">
              <label>商品条码：</label>
              <el-input
                size="small"
                type="text"
                v-model="filingGoodsInfoVO.itemBarcode"
              />
              <span class="new-tips">仅POP填写</span>
            </el-col>

            <el-col class="textarea" :span="12">
              <label class="r">参数规格：</label>
              <el-input type="textarea" maxlength="500" show-word-limit rows="7" v-model="filingGoodsInfoVO.spec"></el-input>
            </el-col>
            <el-col :span="12">
              <el-row>
                <el-col class="textarea">
                  <label class="r">包装清单：</label>
                  <el-input type="textarea" maxlength="500" show-word-limit rows="5" v-model.trim="filingGoodsInfoVO.packingList"></el-input>
                </el-col>
                <el-col>
                  <label class="r">外包装尺寸：</label>
                  <el-input v-model.trim="filingGoodsInfoVO.packageSize" size="small">
                    <template slot="append">mm</template>
                  </el-input>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </div>
        <!-- 其他信息 -->
        <div class="otherInfo">
          <div class="arrow other">其他信息</div>
          <div class="base-list" style="display: flex">
            <label>备注：</label>
            <el-input type="textarea" :rows="5" v-model.trim="filingGoodsInfoVO.remark" />
          </div>
          <div class="tips">若需要填写“节能/环保产品政府采购清单期数及所在页码、行数和证书号”、“生产商”、“产地“或其他信息，请在备注说明</div>
        </div>
        <!-- 其他信息2 --链接和上传 -->
        <div class="otherInfoLink">
          <div class="selectOne">
            <span>至</span>
            <span>少</span>
            <span>填</span>
            <span>一</span>
            <span>项</span>
          </div>
          <div class="linkBox">
            <div class="link">
              <div class="item">
                <label>
                  <i></i> 参考链接：
                </label>
                <!-- <input type="text" v-model="filingGoodsInfoVO.refLink" /> -->
                <el-input type="text" v-model="filingGoodsInfoVO.refLink" size="small" />

              </div>
              <div class="tips">京东/妥了网/天猫/苏宁/国美等链接</div>
            </div>

            <div class="link">
              <div class="item upload">
                <label>
                  <i></i> 产品参考图片：
                </label>
                <upload-img
                  ref="uploadFile"
                  @fileUrlList="fileUrlList"
                  :fileUrlListArr="fileUrlListArr"
                ></upload-img>
              </div>
              <div class="tips uploadTips">若没有提供参考链接，则必须提供3张及以上商品图片</div>
            </div>
          </div>
        </div>
      </div>
      <div class="bottomBtn">
        <div class="btnItem resetBtn" @click="resetData">重置</div>
        <div class="btnItem submitBtn" @click="submitData">提交</div>
      </div>
    </div>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';
import UploadImg from '@/components/public/UpLoadImg.vue'

const getFormData = (data = {}) => {
  return {
    purchasePlatformId: '', // 项目id
    purchasePlatformName: '', // 项目名称
    categoryName: '', // 商品类目名称
    brandName: '', // 商品品牌名称
    goodsName: '', // 商品名称
    model: '', // 商品型号
    num: '', // 商品数量
    unit: '', // 商品单位
    weight: '', // 商品重量KG
    salesPrice: '', // 挂网价（元）
    spec: '', // 商品参考规格
    packingList: '', // 商品包装清单
    refLink: '', // 参考链接 与refImgs必填其中之一
    refImgs: [], // 图片链接集合 与refLink必填其中之一
    itemBarcode: '', // 商品条码
    packageSize: '', // 外包装尺寸
    remark: '', // 备注：节能环保、证书号、生产商产地等其他信息
    ...data,
  }
}

export default {
  props: {
    isTitle: {
      // 是否显示添加商品窗口
      type: Boolean,
      require: true,
      default: false,
    },
    id: {
      // 报备信息 id 添加商品用
      type: Number,
      require: true,
      default: 0,
    },

    isEditWindow: {
      type: Object,
      require: true,
      default: null,
    },
  },
  // import引入的组件需要注入到对象中才能使用
  components: { UploadImg },
  data () {
    // 这里存放数据
    return {
      // 编辑信息
      filingGoodsInfoVO: getFormData(),
      fileUrlListArr: [],
      pointAfter: true,
      searchGoods: [], // 搜索出来的商品
      searchGoodsSelected: null,
      searchGoodsLoading: false,
      showSearchGoods: false,
    }
  },
  created () {},
  mounted () {
    this.initData()
  },
  methods: {
    initData () {
      if (this.isEditWindow.isEditNum) {
        this.getEditData()
      } else {
        this.filingGoodsInfoVO = getFormData()
      }
    },
    // 搜索商品
    async onSearchGoods (query) {
      if (query !== '') {
        this.searchGoodsLoading = true
        try {
          const { result } = await this.$axios({
            methods: 'get',
            url: `/api/createFilingMessage/itemSearch?activityId=${process.env.NODE_ENV === 'development' ? '1004177' : '1004367'}&keyword=${query}`,
          })
          this.searchGoods = [
            // {
            //   id: this.searchGoodsSelected,
            //   type: 0,
            //   itemName: query,
            //   showItemName: query
            // }
          ]
          const tmpEl = document.createElement('div')
          result.forEach(item => {
            tmpEl.innerHTML = item.itemName
            this.searchGoods.push({
              id: item.id,
              type: 1,
              itemName: tmpEl.innerText,
              showItemName: item.itemName,
              minPrice: item.minPrice,
              maxPrice: item.maxPrice,
            })
          })
        } catch (error) {
          console.error(error)
        } finally {
          this.searchGoodsLoading = false
        }
      } else {
        this.searchGoods = []
      }
    },
    onChangeGoods ($event) {
      // console.log('$event', $event)
      this.filingGoodsInfoVO.goodsName = $event
    },
    // 获取编辑信息
    getEditData (id) {
      this.filingGoodsInfoVO = getFormData(this.isEditWindow.data)
      this.searchGoodsSelected = this.filingGoodsInfoVO.goodsName
      this.filingGoodsInfoVO.refImgs = this.evalData(
        this.filingGoodsInfoVO.refImgs,
      )

      if (this.filingGoodsInfoVO.refImgs) {
        this.filingGoodsInfoVO.refImgs.map(item => {
          this.fileUrlListArr.push({ status: 'success', url: item })
        })
      }
    },
    // 关闭弹出窗口
    closeWindow () {
      this.$emit('closedWindow', false)
    },
    // 重置所有信息
    resetData () {
      // 添加商品的重置方法 isShowAddWindow
      this
        .$confirm('确定重置所有信息吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
        .then(() => {
          this.$refs.uploadFile.resetFile()
          this.initData()
          this.successMsg('重置成功')
        })
        .catch(() => {})
    },
    // 提交信息
    async submitData () {
      if (
        !parseFloat(this.filingGoodsInfoVO.num) ||
        !parseFloat(this.filingGoodsInfoVO.salesPrice)
      ) {
        // !parseFloat(this.filingGoodsInfoVO.finalPrice) ||
        this.$alert('请输入正确的数量或价格')
        return
      }

      if (
        !this.filingGoodsInfoVO.weight ||
        !parseFloat(this.filingGoodsInfoVO.weight)
      ) {
        this.$alert('请输入正确的重量信息')
        return
      }
      if (!this.pointAfter) {
        this.$alert('价格请保留小数点后2位数字')
        return
      }
      if (!this.filingGoodsInfoVO.packingList) {
        this.$alert('请输入包装清单')
        return
      }

      if (!this.filingGoodsInfoVO.packageSize) {
        this.$alert('请输入外包装尺寸')
        return
      }

      // 添加数据
      const isMust = this.forEachObj(this.filingGoodsInfoVO)

      if (isMust.mustbe && isMust.refHref) {
        const data = JSON.parse(JSON.stringify(this.filingGoodsInfoVO))
        data.refImgs = JSON.stringify(data.refImgs)
        // this.successMsg('提交成功')

        this.$emit('editData', data)
        this.closeWindow()
      }
    },

    // 重置成功的提示信息
    successMsg (txt) {
      this.$message({
        message: txt,
        type: 'success',
      })
    },
    // 对象遍历
    forEachObj (obj) {
      const _this = this
      const mustObj = {
        mustbe: false, // 必填项
        refHref: false, // 4选1的必填图片
      }
      // 遍历提交的数据,必填项是否全部填写完毕
      for (const i in obj) {
        if (
          i == 'categoryName' ||
          i == 'brandName' ||
          i == 'goodsName' ||
          i == 'model' ||
          i == 'num' ||
          i == 'unit' ||
          i == 'salesPrice' ||
          i == 'spec'
        ) {
          // i == 'finalPrice' ||
          if (!obj[i]) {
            _this.warningAlert()
            return false
          } else {
            mustObj.mustbe = true
          }
          if (
            obj.refLink != '' ||
            obj.refImgs.length >= 3
          ) {
            mustObj.refHref = true
          } else {
            this.$alert(obj.refImgs.length ? '必须提供3张及以上商品图片或者输入正确的参考链接' : '请输入正确的参考链接')
            return false
          }
        }
      }
      return mustObj
    },
    // 警告弹窗,
    warningAlert () {
      this.$alert('还有信息未填写，请填写完后再提交')
    },
    fileUrlList (list) {
      this.filingGoodsInfoVO.refImgs = list
    },
    // 添加商品 初始化信息
    clearAllData () {
      const _this = this
      Object.keys(_this.filingGoodsInfoVO).forEach(key => {
        if (
          _this.filingGoodsInfoVO[key] != '' &&
          key != refImgs &&
          key != id &&
          key != filingId
        ) {
          _this.filingGoodsInfoVO[key] = ''
        } else {
          _this.filingGoodsInfoVO.refImgs = []
          _this.filingGoodsInfoVO.id = 0
          _this.filingGoodsInfoVO.filingId = 0
        }
      })
    },
    // 验证价格小数点后两位
    blurAfter (val) {
      val = val.toString()
      if (val.indexOf('.') != -1) {
        if (val.split('.')[1].length <= 2) {
          this.pointAfter = true
        } else {
          this.pointAfter = false
        }
      } else {
        this.pointAfter = true
      }
    },
  },
  watch: {
    'filingGoodsInfoVO.goodsName' (val, oldValue) {
      if (val === '') {
        this.searchGoods = []
      } else if (val !== oldValue) {
        this.onSearchGoods(val)
      }
    },
  },
}
</script>
<style lang='less' scoped>
@themeColor:#298DF8;
.mask {
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.4);
  position: fixed;
  top: 0;
  left: 0;
  z-index: 5;
}
.new-tips {
  color: #e51c23;
  font-size: 12px;
  padding: 2px 0;
  margin-left: 5px;
}
.tips {
  color: #e51c23;
  font-size: 12px;
  padding: 2px 0;
  padding-left: 100px;
}
.el-input, .el-textarea {
  width: auto;
  flex: 1;
}
.editInfoBox {
  width: 80%;
  border-radius: 5px;
  background: #fff;
  border: 1px solid #bbb;
  position: fixed;
  top: 3%;
  left: 10%;
  z-index: 6;
  .titleBox {
    line-height: 40px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 30px;
    border-bottom: 1px solid #bbb;
    .title {
      font-weight: bold;
      font-size: 14px;
      span {
        color: #e51c23;
      }
    }
    .close {
      font-size: 24px;
      cursor: pointer;
    }
  }
  .productAbout {
    // height: 600px;
    height: 80vh;
    overflow-y: auto;
    .essentialInfo,
    .specPrice,
    .otherInfo {
      position: relative;
      padding-left: 160px;
      .arrow {
        width: 130px;
        height: 40px;
        line-height: 40px;
        -webkit-clip-path: polygon(
          0 0,
          110px 0,
          130px 20px,
          110px 40px,
          0 40px
        );
        background-color: @themeColor;
        color: #fff;
        text-align: center;
        position: absolute;
        left: 0px;
        top: -10px;
      }
      .infoList,
      .spceList,
      .otherList {
        .infoItem,
        .spceItem,
        .otherItem {
          display: flex;
          align-items: center;
          margin-bottom: 10px;
          .name {
            display: inline-block;
            width: 100px;
            text-align: right;
            &:before {
              display: inline-block;
              content: "*";
              color: #e51c23;
            }
          }
          .weight,
          .finalPrice {
            &:before {
              content: "";
            }
          }
          .weightUnit {
            padding: 0 5px;
          }
          input {
            width: 298px;
            height: 30px;
            color: rgba(136, 136, 136, 1);
            font-size: 14px;
            border: 1px solid #bbb;
            padding: 5px;
            color: #888;
          }
          textarea {
            width: 298px;
            height: 60px;
            resize: none;
            padding: 5px;
            color: #888;
          }

        }
        .firstItem {
          display: block;
          .infoTip {
            display: flex;
            align-items: center;
          }
        }
        .thirdItem {
          align-items: baseline;
        }
        .spceItem {
          input {
            width: 110px;
          }
        }
      }
    }
    .essentialInfo {
      margin-top: 25px;
    }
    .specPrice,
    .otherInfo {
      margin-top: 50px;
      .group {
        width: 290px;
      }
      .priceItem {
        .groupTop {
          display: flex;
          align-items: center;
          input {
            margin-left: 4px;
          }
        }
        .tips {
          padding-left: 105px !important;
        }
      }
      .lastItem {
        .group {
          display: flex;
          align-items: baseline;
          flex: 1;
        }
      }
      .otherItem {
        .otherGroup {
          width: 50%;
          padding-left: 50px;
          .aboutCertific {
            margin-top: 10px;
            margin-left: 50px;
          }
          .tips {
            padding-left: 50px;
          }
        }
        .producter {
          padding-left: 40px;
          .tips {
            padding-left: 60px;
          }
        }
      }
    }
    .otherInfoLink {
      // width: 80%;
      padding-left: 115px;
      padding-right: 5%;
      margin: 0 auto;
      margin-top: 15px;
      display: flex;
      .selectOne {
        width: 34px;
        height: 148px;
        font-size: 14px;
        text-align: center;
        padding: 0 5px;
        border-right: 1px solid #bbb;
        margin-top: 10px;
        &:before {
          display: block;
          content: "*";
          color: #e51c23;
        }
        span {
          display: block;
          margin: 5px 0;
        }
      }
      .linkBox {
        width: 100%;
        .link {
          margin-bottom: 10px;
          .item {
            display: flex;
            align-items: center;
            label {
              text-align: right;
              width: 110px;
              position: relative;
              i {
                display: block;
                width: 10px;
                border-top: 1px solid #bbb;
                position: absolute;
                top: 5px;
                left: 0;
                z-index: 4;
              }
            }
            input {
              width: 100%;
            }
          }
          .upload {
            display: flex;
            align-items: flex-start;
            label {
              padding-left: 10px;
            }
          }
        }
        .tips {
          color: #e51c23;
          font-size: 12px;
          padding: 2px 0;
          padding-left: 100px;
        }
        .uploadTips {
          margin-top: 5px;
        }
      }
    }
  }

  .bottomBtn {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    border-top: 1px solid #bbb;
    padding: 10px 0;
    .btnItem {
      width: 100px;
      height: 30px;
      line-height: 30px;
      border-radius: 0px;
      background: #fff;
      color: @themeColor;
      font-size: 14px;
      text-align: center;
      border: 1px solid @themeColor;
      margin-right: 35px;
      cursor: pointer;
    }
    .submitBtn {
      color: #fff;
      background: @themeColor;
    }
  }
}

.base-list {
  width: 95%;
  margin: 0;
  .el-col {
    margin-bottom: 10px;
    display: flex;
    align-items: center;
  }
  label {
    width: 100px;
    text-align: right;
    display: inline-block;
    &.r {
      &::before {
        display: inline-block;
        content: "*";
        color: #e51c23;
      }
    }
  }
  input, textarea  {
    flex: 1;
    color: #888888;
    font-size: 14px;
    border: 1px solid #bbb;
    padding: 5px;
    color: #888;
    margin-right: 10px;
  }
  input {
    height: 30px;
  }
  textarea {
    // lin
  }
  .textarea {
    display: flex;
    align-items: flex-start;
  }
  .tips {
    color: #e51c23;
  }
}
</style>

<style lang="less" scoped>
.infoItem {
  /deep/ .width100 .el-input__inner {
    // width: 750px;
  }
  /deep/ .el-input__inner {
    // width: 298px;
    // height: 30px;
    // color: rgba(136, 136, 136, 1);
    // font-size: 14px;
    // border: 1px solid #bbb;
    // padding: 5px;
    // color: #888;
    // border-radius: 2px;
 }
 /deep/ .el-select__input {
  //  margin-left: 0;
  //  padding: 5px;
 }
}
</style>

<style lang="less">
.color-1 {
  color: #ae0b2a;
}
.show-item-name {
  display: flex;
  &.selected {
    &,  > * {
      font-weight: bold;
    }
  }
  // padding: 6px 12px;

  .item-name {
    flex: 1;
  }
  .price {
    width: 200px;
  }
  a {
    color: #2184dc
  }
 }
</style>
